package service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import bean.Delivery;
import bean.Goods;
import bean.Task;
import bean.User;
import mapper.DeliveryMapper;
import mapper.GoodsMapper;
import mapper.Mapper;
import mapper.TaskMapper;
import mapper.UserMapper;

public class TaskInfoService extends Mapper<TaskMapper> {
	private long total;

	public String getTaskJsonByUserId(int userid, String spage, String startTime, String endTime) {
//		int page = Integer.parseInt(spage);
//		Page<Object> pageHelper = PageHelper.startPage(page, 5);

		Map<String, Object> map = new HashMap<>();
		map.put("userid", userid);
		if (startTime != null && !startTime.isEmpty())
			map.put("startTime", Timestamp.valueOf(startTime + " 00:00:00"));
		if (endTime != null && !endTime.isEmpty())
			map.put("endTime", Timestamp.valueOf(endTime + " 00:00:00"));
		List<Task> tasks = getMapper().findByUserId(map);
//		total = pageHelper.getTotal();

		String json = listToJson(tasks);
		return json;
	}

	public String getAllTaskJson(String spage, String startTime, String endTime, String taskno, String transportStatus,
			String payStatus, String applyStatus, String lackStatus, String addressee, String payno) {
//		int page = Integer.parseInt(spage);
//		Page<Object> pageHelper = PageHelper.startPage(page, 3);

		Map<String, Object> map = new HashMap<>();
		if (startTime != null && !startTime.isEmpty())
			map.put("startTime", Timestamp.valueOf(startTime + " 00:00:00"));
		if (endTime != null && !endTime.isEmpty())
			map.put("endTime", Timestamp.valueOf(endTime + " 00:00:00"));
		map.put("taskno", taskno);
		map.put("transportStatus", transportStatus);
		map.put("payStatus", payStatus);
		map.put("applyStatus", applyStatus);
		map.put("lackStatus", lackStatus);
		map.put("addressee", addressee);
		map.put("payno", payno);

		List<Task> tasks = getMapper().findAll(map);
//		total = pageHelper.getTotal();

		String json = listToJson(tasks);
		return json;
	}

	public String getPayMoneyJson(int userId) {
		Double money = getMapper().getPayMoney(userId);
		if (money == null)
			money = 0d;
		String json = new Gson().toJson(money);
		return json;
	}

	// 获取欠款json
	public String getLackMoneyJson(int userId) {
		Double money = getMapper().getLackMoney(userId);
		if (money == null)
			money = 0d;
		Double freightMoney = getMapper().getLackFreightMoney(userId);
		if (freightMoney == null)
			freightMoney = 0d;
		money += freightMoney;
		String json = new Gson().toJson(money);
		return json;
	}

	// 任务列表转json
	private String listToJson(List<Task> tasks) {
		UserMapper userMapper = new UserInfoService().getMapper();
		GoodsMapper goodsMapper = new GoodsInfoService().getMapper();
		Gson gson = new Gson();
		JsonElement jsonTree = gson.toJsonTree(tasks);
		JsonArray jsonArray = jsonTree.getAsJsonArray();
		Iterator<JsonElement> iterator = jsonArray.iterator();
		while (iterator.hasNext()) {
			JsonObject jsonObject = iterator.next().getAsJsonObject();
			// 添加客户信息
			JsonElement userJsonTree = gson.toJsonTree(userMapper.findById(jsonObject.get("user_id").getAsInt()));
			jsonObject.add("user", userJsonTree);
			// 添加商品信息
			JsonElement goodsJsonTree = gson.toJsonTree(goodsMapper.findById(jsonObject.get("goods_id").getAsInt()));
			jsonObject.add("goods", goodsJsonTree);
		}
		// 总数
		String totalJson = "{'total':" + total + "}";
		JsonObject totalObject = new JsonParser().parse(totalJson).getAsJsonObject();
		jsonArray.add(totalObject);
		return gson.toJson(jsonArray);
	}

	public String getTaskJsonByStatus(int userid, String condition, String spage, String startTime, String endTime) {
//		int page = Integer.parseInt(spage);
//		Page<Object> pageHelper = PageHelper.startPage(page, 5);

		Map<String, Object> map = new HashMap<>();
		map.put("userid", userid);
		if (startTime != null && !startTime.isEmpty())
			map.put("startTime", Timestamp.valueOf(startTime + " 00:00:00"));
		if (endTime != null && !endTime.isEmpty())
			map.put("endTime", Timestamp.valueOf(endTime + " 00:00:00"));

		List<Task> tasks = new ArrayList<>();
		switch (condition) {
		case "delivery":
			tasks = getMapper().findApply(map);
			break; // 未领货
		case "applied":
			tasks = getMapper().findApplied(map);
			break;// 未发货
		case "lack":
			tasks = getMapper().findLack(map);
			break;// 缺货
		}

//		total = pageHelper.getTotal();
		String json = listToJson(tasks);
		return json;
	}

	// 领货操作
	public void deliveryTask(String[] tasknos, String address, String addressee, String tel) {
		for (String taskno : tasknos) {
			Map<String, Object> map = new HashMap<>();
			map.put("taskno", taskno);
			map.put("address", address);
			map.put("addressee", addressee);
			map.put("tel", tel);
			getMapper().deliveryTask(map);
		}
	}

	// 改变订单状态
	public void changeStatus(String[] tasknos, String operation) {
		for (String taskno : tasknos) {
			Map<String, Object> map = new HashMap<>();
			map.put("taskno", taskno);
			switch (operation) {
			case "pay":
				getMapper().pay(map);
				break;
			case "payback":
				getMapper().payback(map);
				break;
			case "transportover":
				getMapper().transportover(map);
				getMapper().transportoverAndDelivery(map);
				break;
			case "lack":
				getMapper().lack(map);
				break;
			case "del":
				getMapper().delTask(map);
				break;
			}
		}
	}

	public void addTask(String taskno, String username, String brand, String type, String price, String color,
			String size, String freight, String totalPrice, String payNo, String goodsname, String imgurl,
			String goodsNumber, String time, String taskprice) {
		GoodsMapper goodsMapper = new GoodsInfoService().getMapper();
		UserMapper userMapper = new UserInfoService().getMapper();
		Goods goods = new Goods();
		goods.setBrand(brand);
		goods.setColor(color);
		goods.setName(goodsname);
		goods.setPic(imgurl);
		goods.setPrice(Double.parseDouble(price));
		goods.setSize(size);
		goods.setType(type);
		goodsMapper.addGoods(goods);
		int goods_id = goods.getId();
		Task task = new Task();
		task.setNo(taskno);
		task.setUser_id(userMapper.findByName(username).getId());
		task.setGoods_id(goods_id);
		task.setFreight(Double.parseDouble(freight));
		task.setGoodsNumber(Integer.parseInt(goodsNumber));
		task.setPayNo(payNo);
		task.setTime(Timestamp.valueOf(time + " 00:00:00"));
		task.setTransportStatus("2");
		task.setApplyStatus("1");
		task.setPayStatus("1");
		task.setLackStatus("1");
		task.setPrice(Double.parseDouble(taskprice));
		task.setIsPayFreight("0");
		Double totalPriceByPayNo = getMapper().getTotalPriceByPayNo(payNo);
		if (totalPriceByPayNo != null)
			task.setTotalPrice(totalPriceByPayNo + Double.parseDouble(taskprice));
		else 
			task.setTotalPrice(Double.parseDouble(taskprice));
		Map<String, Object> map = new HashMap<>();
		map.put("totalPrice", task.getTotalPrice());
		map.put("payNo", task.getPayNo());
		getMapper().updateTotalPriceByPayNo(map);
		// 添加用户默认信息
		User user = userMapper.findById(task.getUser_id());
		task.setAddr(user.getAddr());
		task.setTel(user.getTel());
		task.setAddressee(user.getUsername());
		
		getMapper().addTask(task);
	}

	// 已发货操作
	public void deliveried(String[] tasknos, String deliveryno, String payNo, String freight) {
		DeliveryMapper deliveryMapper = new DeliveryInfoService().getMapper();
		// 查询是否有相同单号
		Delivery delivery = deliveryMapper.findByNo(deliveryno);
		if (delivery == null) {
			// 新建发货单
			delivery = new Delivery();
			delivery.setNo(deliveryno);
			delivery.setDate(new Timestamp(new Date().getTime()));
			delivery.setNumber(tasknos.length);
			delivery.setPayNo(payNo);
			delivery.setFreight(freight);
			deliveryMapper.addDelivery(delivery);
		}else {
			delivery.setDate(new Timestamp(new Date().getTime()));
			delivery.setNumber(delivery.getNumber() + tasknos.length);
			deliveryMapper.updateDelivery(delivery);
		}
		// 更新订单信息
		for (String taskno : tasknos) {
			Map<String, Object> map = new HashMap<>();
			map.put("taskno", taskno);
			map.put("delivery_no", deliveryno);
			getMapper().deliveried(map);
			if (getMapper().findByTaskNo(taskno).getIsPayFreight().equals("1"))
				deliveryMapper.isPay(deliveryno);
		}
	}
}
